{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<h1> Training flight delay model in BigQuery ML </h1>\n",
    "\n",
    "Run this notebook in Cloud AI Platform Notebooks. In this notebook, we will use BigQuery ML to train the same model that we did in Spark ML.\n",
    "\n",
    "Note how much easier this is ... (and also much more scaleable)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Verify dataset\n",
    "\n",
    "Let's make sure that we have the traindays and flights data in BigQuery. If you don't, please follow steps in the README.md in this directory."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%bigquery\n",
    "SELECT * FROM flights.tzcorr\n",
    "LIMIT 5"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%bigquery\n",
    "SELECT * FROM flights.trainday\n",
    "LIMIT 5"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<h2> Logistic regression </h2>\n",
    "\n",
    "This query will take about 10 minutes."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "%%bigquery\n",
    "CREATE OR REPLACE MODEL flights.arr_delay_lm\n",
    "OPTIONS(input_label_cols=['ontime'], \n",
    "        model_type='logistic_reg', \n",
    "        data_split_method='custom',\n",
    "        data_split_col='is_eval_day')\n",
    "AS\n",
    "\n",
    "SELECT\n",
    "  IF(arr_delay < 15, 'ontime', 'late') AS ontime\n",
    "  , dep_delay\n",
    "  , taxi_out\n",
    "  , distance\n",
    "  , IF(is_train_day = 'True', False, True) AS is_eval_day\n",
    "FROM flights.tzcorr f\n",
    "JOIN flights.trainday t\n",
    "ON f.FL_DATE = t.FL_DATE\n",
    "WHERE\n",
    "  f.CANCELLED = '0.00' AND \n",
    "  f.DIVERTED = '0.00'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "%%bigquery\n",
    "SELECT * \n",
    "FROM ML.EVALUATE(MODEL flights.arr_delay_lm,\n",
    "                 (\n",
    "SELECT\n",
    "  IF(arr_delay < 15, 'ontime', 'late') AS ontime\n",
    "  , dep_delay\n",
    "  , taxi_out\n",
    "  , distance\n",
    "FROM flights.tzcorr f\n",
    "JOIN flights.trainday t\n",
    "ON f.FL_DATE = t.FL_DATE\n",
    "WHERE\n",
    "  f.CANCELLED = '0.00' AND \n",
    "  f.DIVERTED = '0.00' AND\n",
    "  t.is_train_day = 'False'\n",
    "                 ),\n",
    "                 STRUCT(0.7 AS threshold))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Do same metrics as in Spark code\n",
    "\n",
    "We are using ML.PREDICT and computing the necessary stats"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%bigquery\n",
    "\n",
    "WITH predictions AS (\n",
    "SELECT \n",
    "  *\n",
    "FROM ML.PREDICT(MODEL flights.arr_delay_lm,\n",
    "                 (\n",
    "SELECT\n",
    "  IF(arr_delay < 15, 'ontime', 'late') AS ontime\n",
    "  , dep_delay\n",
    "  , taxi_out\n",
    "  , distance\n",
    "FROM flights.tzcorr f\n",
    "JOIN flights.trainday t\n",
    "ON f.FL_DATE = t.FL_DATE\n",
    "WHERE\n",
    "  f.CANCELLED = '0.00' AND \n",
    "  f.DIVERTED = '0.00' AND\n",
    "  t.is_train_day = 'False'\n",
    "                 ),\n",
    "                 STRUCT(0.7 AS threshold))),\n",
    "\n",
    "stats AS (\n",
    "SELECT \n",
    "  COUNTIF(ontime != 'ontime' AND ontime = predicted_ontime) AS correct_cancel\n",
    "  , COUNTIF(predicted_ontime = 'ontime') AS total_noncancel\n",
    "  , COUNTIF(ontime = 'ontime' AND ontime = predicted_ontime) AS correct_noncancel\n",
    "  , COUNTIF(ontime != 'ontime') AS total_cancel\n",
    "  , SQRT(SUM((IF(ontime = 'ontime', 1, 0) - p.prob) * (IF(ontime = 'ontime', 1, 0) - p.prob))/COUNT(*)) AS rmse\n",
    "FROM predictions, UNNEST(predicted_ontime_probs) p\n",
    "WHERE p.label = 'ontime'\n",
    ")\n",
    "\n",
    "SELECT\n",
    "   correct_cancel / total_cancel AS correct_cancel\n",
    "   , total_noncancel\n",
    "   , correct_noncancel / total_noncancel AS correct_noncancel\n",
    "   , total_cancel\n",
    "   , rmse\n",
    "FROM stats"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Add airport info\n",
    "\n",
    "Add airport information to model (note two additional columns: origin and dest). This seemingly simple change adds two categorical variables that, when one-hot-encoded, adds 600+ new columns to the model. BigQuery ML doesn't skip a beat ..."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%bigquery\n",
    "CREATE OR REPLACE MODEL flights.arr_delay_airports_lm\n",
    "OPTIONS(input_label_cols=['ontime'], \n",
    "        model_type='logistic_reg', \n",
    "        data_split_method='custom',\n",
    "        data_split_col='is_eval_day')\n",
    "AS\n",
    "\n",
    "SELECT\n",
    "  IF(arr_delay < 15, 'ontime', 'late') AS ontime\n",
    "  , dep_delay\n",
    "  , taxi_out\n",
    "  , distance\n",
    "  , origin\n",
    "  , dest\n",
    "  , IF(is_train_day = 'True', False, True) AS is_eval_day\n",
    "FROM flights.tzcorr f\n",
    "JOIN flights.trainday t\n",
    "ON f.FL_DATE = t.FL_DATE\n",
    "WHERE\n",
    "  f.CANCELLED = '0.00' AND \n",
    "  f.DIVERTED = '0.00'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%bigquery\n",
    "SELECT * \n",
    "FROM ML.EVALUATE(MODEL flights.arr_delay_airports_lm,\n",
    "                 (\n",
    "SELECT\n",
    "  IF(arr_delay < 15, 'ontime', 'late') AS ontime\n",
    "  , dep_delay\n",
    "  , taxi_out\n",
    "  , distance\n",
    "  , origin\n",
    "  , dest\n",
    "FROM flights.tzcorr f\n",
    "JOIN flights.trainday t\n",
    "ON f.FL_DATE = t.FL_DATE\n",
    "WHERE\n",
    "  f.CANCELLED = '0.00' AND \n",
    "  f.DIVERTED = '0.00' AND\n",
    "  t.is_train_day = 'False'\n",
    "                 ),\n",
    "                 STRUCT(0.7 AS threshold))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%bigquery\n",
    "\n",
    "WITH predictions AS (\n",
    "SELECT \n",
    "  *\n",
    "FROM ML.PREDICT(MODEL flights.arr_delay_airports_lm,\n",
    "                 (\n",
    "SELECT\n",
    "  IF(arr_delay < 15, 'ontime', 'late') AS ontime\n",
    "  , dep_delay\n",
    "  , taxi_out\n",
    "  , origin\n",
    "  , dest\n",
    "  , distance\n",
    "FROM flights.tzcorr f\n",
    "JOIN flights.trainday t\n",
    "ON f.FL_DATE = t.FL_DATE\n",
    "WHERE\n",
    "  f.CANCELLED = '0.00' AND \n",
    "  f.DIVERTED = '0.00' AND\n",
    "  t.is_train_day = 'False'\n",
    "                 ),\n",
    "                 STRUCT(0.7 AS threshold))),\n",
    "\n",
    "stats AS (\n",
    "SELECT \n",
    "  COUNTIF(ontime != 'ontime' AND ontime = predicted_ontime) AS correct_cancel\n",
    "  , COUNTIF(predicted_ontime = 'ontime') AS total_noncancel\n",
    "  , COUNTIF(ontime = 'ontime' AND ontime = predicted_ontime) AS correct_noncancel\n",
    "  , COUNTIF(ontime != 'ontime') AS total_cancel\n",
    "  , SQRT(SUM((IF(ontime = 'ontime', 1, 0) - p.prob) * (IF(ontime = 'ontime', 1, 0) - p.prob))/COUNT(*)) AS rmse\n",
    "FROM predictions, UNNEST(predicted_ontime_probs) p\n",
    "WHERE p.label = 'ontime'\n",
    ")\n",
    "\n",
    "SELECT\n",
    "   correct_cancel / total_cancel AS correct_cancel\n",
    "   , total_noncancel\n",
    "   , correct_noncancel / total_noncancel AS correct_noncancel\n",
    "   , total_cancel\n",
    "   , rmse\n",
    "FROM stats"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Note that the addition of the airports information has improved both the AUC and the RMSE"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Deep Neural Network\n",
    "\n",
    "This is from Chapter 9, but in order to keep all the BigQuery ML stuff in one place, I'm updating the Chapter 7 notebook.\n",
    "\n",
    "Let's train a DNN model instead of a linear model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%bigquery\n",
    "CREATE OR REPLACE MODEL flights.arr_delay_airports_dnn\n",
    "OPTIONS(input_label_cols=['ontime'], \n",
    "        model_type='dnn_classifier',\n",
    "        hidden_units=[64, 8],\n",
    "        data_split_method='custom',\n",
    "        data_split_col='is_eval_day')\n",
    "AS\n",
    "\n",
    "SELECT\n",
    "  IF(arr_delay < 15, 'ontime', 'late') AS ontime\n",
    "  , dep_delay\n",
    "  , taxi_out\n",
    "  , distance\n",
    "  , origin\n",
    "  , dest\n",
    "  , IF(is_train_day = 'True', False, True) AS is_eval_day\n",
    "FROM flights.tzcorr f\n",
    "JOIN flights.trainday t\n",
    "ON f.FL_DATE = t.FL_DATE\n",
    "WHERE\n",
    "  f.CANCELLED = '0.00' AND \n",
    "  f.DIVERTED = '0.00'"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "And evaluate this model as before"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%bigquery\n",
    "\n",
    "WITH predictions AS (\n",
    "SELECT \n",
    "  *\n",
    "FROM ML.PREDICT(MODEL flights.arr_delay_airports_lm,\n",
    "                 (\n",
    "SELECT\n",
    "  IF(arr_delay < 15, 'ontime', 'late') AS ontime\n",
    "  , dep_delay\n",
    "  , taxi_out\n",
    "  , origin\n",
    "  , dest\n",
    "  , distance\n",
    "FROM flights.tzcorr f\n",
    "JOIN flights.trainday t\n",
    "ON f.FL_DATE = t.FL_DATE\n",
    "WHERE\n",
    "  f.CANCELLED = '0.00' AND \n",
    "  f.DIVERTED = '0.00' AND\n",
    "  t.is_train_day = 'False'\n",
    "                 ),\n",
    "                 STRUCT(0.7 AS threshold))),\n",
    "\n",
    "stats AS (\n",
    "SELECT \n",
    "  COUNTIF(ontime != 'ontime' AND ontime = predicted_ontime) AS correct_cancel\n",
    "  , COUNTIF(predicted_ontime = 'ontime') AS total_noncancel\n",
    "  , COUNTIF(ontime = 'ontime' AND ontime = predicted_ontime) AS correct_noncancel\n",
    "  , COUNTIF(ontime != 'ontime') AS total_cancel\n",
    "  , SQRT(SUM((IF(ontime = 'ontime', 1, 0) - p.prob) * (IF(ontime = 'ontime', 1, 0) - p.prob))/COUNT(*)) AS rmse\n",
    "FROM predictions, UNNEST(predicted_ontime_probs) p\n",
    "WHERE p.label = 'ontime'\n",
    ")\n",
    "\n",
    "SELECT\n",
    "   correct_cancel / total_cancel AS correct_cancel\n",
    "   , total_noncancel\n",
    "   , correct_noncancel / total_noncancel AS correct_noncancel\n",
    "   , total_cancel\n",
    "   , rmse\n",
    "FROM stats"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Copyright 2019 Google Inc. Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
